package com.oinux.playhelper.ui;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.oinux.playhelper.R;
import com.oinux.playhelper.app.BaseActivity;
import com.oinux.playhelper.db.DatabaseHelper;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.entity.AppStat;
import com.oinux.playhelper.util.DensityUtil;
import com.oinux.playhelper.util.ScreenShot;
import com.oinux.playhelper.util.TimeUtils;
import com.oinux.playhelper.widget.YesOrNoDialog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMSsoHandler;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;

public class AppDetail extends BaseActivity implements OnClickListener {

	private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
	private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
	private TimeSeries mCurrentSeries;
	private XYSeriesRenderer mCurrentRenderer;
	private GraphicalView mChartView;

	private TextView titleText;
	private TextView totalRuntimeText;
	private TextView currentRuntimeText;
	private TextView memoryText;
	private TextView chartNameText;
	private Button shutdownAppBtn;
	private Button crashAppBtn;
	private RelativeLayout memory;

	private DatabaseHelper databaseHelper = null;
	private int appId;
	private String imagePath;
	private String appName;

	final UMSocialService mController = UMServiceFactory.getUMSocialService(
			"com.umeng.share", RequestType.SOCIAL);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_detail);
		initView();
		initData();
		initShare();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (databaseHelper != null) {
			OpenHelperManager.releaseHelper();
			databaseHelper = null;
		}
	}

	private void initShare() {
		mController.getConfig().removePlatform(SHARE_MEDIA.EMAIL,
				SHARE_MEDIA.SMS);
		/** 微信支持 **/
		String appID = "wx83c398197a1722cd";
		String contentUrl = "http://www.oinux.com:8080/static/playhelper/index.html";
		mController.getConfig().supportWXPlatform(this, appID, contentUrl);
		mController.getConfig()
				.supportWXCirclePlatform(this, appID, contentUrl);
		/** QQ支持 **/
		mController.getConfig().supportQQPlatform(this,
				"http://www.oinux.com:8080/static/playhelper/index.html");
		/** SSO登陆 **/
		mController.getConfig().setSsoHandler(new QZoneSsoHandler(this));
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
	}

	private void setShare() {
		mController.setShareContent("这是我通过“玩手机助手”记录" + appName
				+ "的运行时间折线图，小伙伴们也快去试试吧，下载地址：http://www.oinux.com:8080/static/playhelper/index.html");
		mController.setShareMedia(new UMImage(this, BitmapFactory
				.decodeFile(imagePath)));
	}

	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
			databaseHelper = OpenHelperManager.getHelper(this,
					DatabaseHelper.class);
		}
		return databaseHelper;
	}

	private void initData() {
		appId = getIntent().getIntExtra("app_id", -1);
		Date now = new Date();
		AppInfo appInfo = null;
		List<AppStat> appStats = null;
		try {
			appInfo = getHelper().getAppInfoDao().queryForId(appId);
			QueryBuilder<AppStat, Integer> queryBuilder = getHelper()
					.getAppStatDao().queryBuilder();
			queryBuilder.where().eq("appInfo_id", appInfo.getId()).and()
					.ge("startTime", TimeUtils.getDateBefore(now, 30));
			PreparedQuery<AppStat> preparedQuery = queryBuilder.prepare();
			appStats = getHelper().getAppStatDao().query(preparedQuery);
			appName = appInfo.getName();
			chartNameText.setText(appName + "的运行时间折线图");
			long total = appInfo.getTotalTime();
			long current = appInfo.getRunTime();
			totalRuntimeText.setText(TimeUtils.formatTime(total + current));
			currentRuntimeText.setText(TimeUtils.formatTime(current));
			if (!appInfo.isRunning()) {
				memory.setVisibility(View.GONE);
			} else
				memoryText.setText(String.format("%.2fMB",
						appInfo.getMemSize() / 1000d));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Date[] xvalues = new Date[30];
		double[] yvalues = new double[30];
		for (int i = 0; i < xvalues.length; i++) {
			xvalues[i] = TimeUtils.getDateBefore(TimeUtils.getTodayZero(), i);
		}
		for (int i = 0; i < yvalues.length; i++) {
			for (AppStat appStat : appStats) {
				Date startTime = appStat.getStartTime();
				Date eTime = TimeUtils.getDateAfter(xvalues[i], 1);
				if (startTime.after(xvalues[i]) && startTime.before(eTime)) {
					Date finishTime = appStat.getFinishTime() == null ? now
							: appStat.getFinishTime();
					yvalues[i] += finishTime.getTime() - startTime.getTime();
				}
			}
			yvalues[i] = (double) yvalues[i] / TimeUtils.DIVIDE_TO_HOUR;
		}

		int chartBackground = getResources().getColor(
				R.color.app_detail_chart_bg_wz);
		if (getThemeId() == R.style.qinxin) {
			chartBackground = getResources().getColor(
					R.color.app_detail_chart_bg_qinxin);
		}
		mRenderer.setApplyBackgroundColor(true);
		// 曲线中间背景颜色
		mRenderer.setBackgroundColor(chartBackground);
		// XYSeries标题的大小
		mRenderer.setShowLegend(false);
		mRenderer.setLabelsTextSize(DensityUtil.dip2px(this, 13));
		// y轴标量距离y轴的宽度
		mRenderer.setYLabelsPadding(DensityUtil.dip2px(this, 13));
		// 设置y轴标量相对于原来高度的高度
		mRenderer.setYLabelsVerticalPadding(DensityUtil.dip2px(this, -3));
		// 上、左、下、右
		mRenderer.setMargins(new int[] { DensityUtil.dip2px(this, 10),
				DensityUtil.dip2px(this, 45), DensityUtil.dip2px(this, 20),
				DensityUtil.dip2px(this, 30) });
		// 曲线四周背景颜色
		mRenderer.setMarginsColor(chartBackground);
		mRenderer.setYAxisMax(24);
		// xy轴颜色
		mRenderer.setAxesColor(getResources().getColor(
				R.color.app_detail_chart_xy));
		// x轴标量颜色
		mRenderer.setXLabelsColor(getResources().getColor(
				R.color.app_detail_chart_text));
		// y轴标量颜色
		mRenderer.setYLabelsColor(0,
				getResources().getColor(R.color.app_detail_chart_text));
		mRenderer.setXRoundedLabels(false);
		mRenderer.setSelectableBuffer(10);
		mRenderer.setZoomButtonsVisible(false);
		mRenderer.setClickEnabled(false);
		mRenderer.setZoomEnabled(false);
		mRenderer.setPanEnabled(false);
		mRenderer.setInScroll(true);

		mCurrentSeries = new TimeSeries(appInfo.getName() + "的运行时间折线图");
		for (int i = 0; i < xvalues.length; i++)
			mCurrentSeries.add(xvalues[i], yvalues[i]);
		mDataset.addSeries(mCurrentSeries);
		mCurrentRenderer = new XYSeriesRenderer();
		// 曲线颜色
		mCurrentRenderer.setColor(getResources().getColor(
				R.color.app_detail_chart_line));
		mCurrentRenderer.setLineWidth(3.2f);
		mRenderer.addSeriesRenderer(mCurrentRenderer);
	}

	private void initView() {
		titleText = (TextView) findViewById(R.id.title_bar_text);
		titleText.setText(R.string.app_detail);
		totalRuntimeText = (TextView) findViewById(R.id.total_run_time_text);
		currentRuntimeText = (TextView) findViewById(R.id.current_run_time_text);
		chartNameText = (TextView) findViewById(R.id.chart_name);
		memoryText = (TextView) findViewById(R.id.memory_status_text);
		memory = (RelativeLayout) findViewById(R.id.memory);
		shutdownAppBtn = (Button) findViewById(R.id.shutdown_app_btn);
		shutdownAppBtn.setOnClickListener(this);
		crashAppBtn = (Button) findViewById(R.id.crash_app_btn);
		crashAppBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == shutdownAppBtn) {
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				imagePath = ScreenShot.shoot(this);
				setShare();
				mController.openShare(this, false);
			} else {
				Toast.makeText(this, "SD卡未挂载，不能截图", Toast.LENGTH_SHORT).show();
			}
		} else if (v == crashAppBtn) {
			YesOrNoDialog.Builder builder = new YesOrNoDialog.Builder(this);
			builder.setMessage(R.string.crash_tip).setTitle(R.string.crash);
			builder.setNegativeButton(R.string.no,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.setPositiveButton(R.string.yes,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							crash();
							initData();
						}
					});
			builder.create().show();
		}
	}

	private void crash() {
		try {
			Dao<AppInfo, Integer> appInfoDao = getHelper().getAppInfoDao();
			Dao<AppStat, Integer> appStatDao = getHelper().getAppStatDao();
			AppInfo appInfo = appInfoDao.queryForId(appId);
			appInfo.setRunTime(0);
			appInfo.setRunning(false);
			appInfo.setTotalTime(0);
			appInfoDao.update(appInfo);
			DeleteBuilder<AppStat, Integer> deleteAppStat = appStatDao
					.deleteBuilder();
			deleteAppStat.where().eq("appInfo_id", appId);
			appStatDao.delete(deleteAppStat.prepare());
			initData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mChartView == null) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			mChartView = ChartFactory.getTimeChartView(this, mDataset,
					mRenderer, "MM.dd");
			layout.addView(mChartView, new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		} else {
			mChartView.repaint();
		}
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

}